package weaver.aiyh_pcn.copy_attachment;

import aiyh.utils.Util;
import aiyh.utils.mapUtil.ParaMap;
import aiyh.utils.sqlUtil.sqlResult.impl.PrepSqlResultImpl;
import aiyh.utils.zwl.common.ToolUtil;
import com.api.aiyh_pcn.copy_attachment.dao.DocTemplateDao;
import com.api.aiyh_pcn.copy_attachment.model.ConfigEmpty;
import org.h2.util.StringUtils;
import weaver.conn.RecordSet;
import weaver.hrm.User;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/11/8 0008 15:38
 * baomixieyi
 */


public class CopyAttachmentSecretAction extends ToolUtil implements Action {
	//	模板id
	private String attachmentTemplateId;
	//	是否属于浏览框
	private String isBrowseBox;
	//	第一次添加附件标识字段
	private String firstAddField;
	//	第一次添加附件的值
	private String firstAddValue;
	//	第一次添加成功后的回写值
	private String addSuccessValue;
	//	安全协议单独id字段
	private String secretField;

	@Override
	public String execute(RequestInfo requestInfo) {
		ToolUtil toolUtil = new ToolUtil();

		try {
			User user = requestInfo.getRequestManager().getUser();
			String billTableName = requestInfo.getRequestManager().getBillTableName();
			String requestId = requestInfo.getRequestid();
			String workflowId = requestInfo.getWorkflowid();
			RecordSet rs_1 = new RecordSet();
//		查询流程数据
			String query = "select * from " + billTableName + " where requestid = ?";
			toolUtil.writeDebuggerLog("进入保密协议action！");
			rs_1.executeQuery(query, requestId);
			Map<String, Object> requestData = Util.recordSet2Map(rs_1);
			toolUtil.writeDebuggerLog(requestData.toString());
//			如果不是第一次添加，则直接返回  隐藏bug，如果用户第一次选择添加，后面被退回后，将附件清空了，重新上传，然后又需要安全协议，但是已经不是第一次添加了，所以并不会生效
			if (StringUtils.isNullOrEmpty(secretField)) {
				if (requestData.get(firstAddField) != null && !Util.null2String(firstAddValue).equals(String.valueOf(requestData.get(firstAddField)))) {
					return Action.SUCCESS;
				}
			}
//		查询配置表，获取配置数据
			String querySql = "select ufta.id,ufta.workflow_type,wftva.fieldname as template_field,  " +
					"wftvb.fieldname as attachment_field,wftv.fieldname as show_field, wftvb.id as attachment_field_id,  " +
					"ufta.is_template_show,ufta.model_table_name, ufta.model_field,wsl.selectvalue as show_value,  " +
					"wftv.tablename as show_table_name,wftva.tablename as template_table_name,wftvb.tablename as attachment_table_name,  " +
					"wsla.selectvalue as hidden_value from uf_temp_attachment as ufta  " +
					"left join workflow_selectitem as wsl on wsl.id = ufta.show_value " +
					"left join workflow_selectitem as wsla on wsla.id = ufta.hidden_value " +
					"left join workflow_field_table_view as wftv on wftv.id = ufta.show_field " +
					"left join workflow_field_table_view as wftva on wftva.id = ufta.template_field " +
					"left join workflow_field_table_view as wftvb on wftvb.id = ufta.attachment_field " +
					"where workflow_type in " +
					"(select id from workflow_base where activeVersionID in " +
					"(select activeVersionID  from workflow_base where id = ?) or id = ?) and attachment_type = ?";
			RecordSet rs = new RecordSet();
			rs.executeQuery(querySql, workflowId, workflowId, 1);
			ConfigEmpty configEmpty = null;
			while (rs.next()) {
//			    id
				int id = Util.getIntValue(rs.getString("id"));
//			    显示值
				int showValue = Util.getIntValue(rs.getString("show_value"));
//			    隐藏值
				int hiddenValue = Util.getIntValue(rs.getString("hidden_value"));
//			    流程id
				String workflowType = rs.getString("workflow_type");
//			    模板字段
				String templateField = rs.getString("template_field");
//			    附件字段
				String attachmentField = rs.getString("attachment_field");
//			    是否用字段控制模板
				String isTemplateShow = rs.getString("is_template_show");
//			    模板建模表表名
				String modelTableName = rs.getString("model_table_name");
//			    控制模板显示与否的字段
				String showField = rs.getString("show_field");
//			    建模表福建模板字段
				String modelField = rs.getString("model_field");
//			    控制显示所在表
				String showTableName = rs.getString("show_table_name");
//			    模板字段所在表
				String templateTableName = rs.getString("template_table_name");
//			    附件字段所在表
				String attachmentTableName = rs.getString("attachment_table_name");
//			    附件字段id
				String attachmentFieldId = rs.getString("attachment_field_id");
				toolUtil.writeDebuggerLog("保密协议已经查询到数据！");

				configEmpty = ConfigEmpty.create()
						.id(id)
						.showValue(showValue)
						.hiddenValue(hiddenValue)
						.workflowType(workflowType)
						.templateField(templateField)
						.attachmentField(attachmentField)
						.isTemplateShow(isTemplateShow)
						.modelTableName(modelTableName)
						.showField(showField)
						.modelField(modelField)
						.showTableName(showTableName)
						.templateTableName(templateTableName)
						.attachmentTableName(attachmentTableName)
						.attachmentFieldId(attachmentFieldId)
						.builder();
				if (!StringUtils.isNullOrEmpty(secretField)) {
					//				原字段的文件id
					String fileIds = Util.null2String(rs_1.getString(configEmpty.getAttachmentField()));
					String[] split = fileIds.split(",");
//				转为list
					List<String> list = Arrays.stream(split).collect(Collectors.toList());
//				如果配置了secretField字段
					if (!StringUtils.isNullOrEmpty(secretField)) {
						String secretIds = Util.null2String(rs_1.getString(secretField));
						String[] secretIdArr = secretIds.split(",");
						List<String> secretFieldList = Arrays.stream(secretIdArr).collect(Collectors.toList());
						list.removeAll(secretFieldList);
					}
					Map<String, Object> data = ParaMap.create().put(configEmpty.getAttachmentField(), String.join(",", list));
//			修改流程数据，将保密协议的docid更新到流程中
					PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(billTableName,
							data,
							Util.createPrepWhereImpl().whereAnd("requestid").whereEqual(requestId));
					toolUtil.writeDebuggerLog("sql ： " + sqlResult.getSqlStr() + "  参数： ---> " + sqlResult.getArgs());
					rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
				}
				toolUtil.writeDebuggerLog("保密协议数据：" + configEmpty.toString());
//			    如果不控制是否使用模板，那就默认不添加保密协议
				if ("1".equals(isTemplateShow)) {
//				不使用模板
					toolUtil.writeDebuggerLog("不使用安全协议数据！因为不控制模板的使用！");
					return Action.SUCCESS;
				}
				String showFieldValue = String.valueOf(requestData.get(configEmpty.getShowField()));
//			不使用保密协议模板
				if (configEmpty.getShowValue() != Integer.parseInt(showFieldValue)) {
					toolUtil.writeDebuggerLog("不使用安全协议数据！因为不使用保密协议！");
					return Action.SUCCESS;
				}
			}
			if (configEmpty != null) {
//			使用保密协议模板
				String docIds = copyFile(user, configEmpty, String.valueOf(requestData.get(configEmpty.getTemplateField())));
				toolUtil.writeDebuggerLog("复制完成文件id：" + docIds);
				if (StringUtils.isNullOrEmpty(docIds)) {
					requestInfo.getRequestManager().setMessageid("1");
//				TODO 修改htmlLabel
					requestInfo.getRequestManager().setMessagecontent(aiyh.utils.Util.getHtmlLabelName(-87783, user.getLanguage(), "保密协议复制失败，未能正确复制保密协议！"));
					return Action.FAILURE_AND_CONTINUE;
				}
//				原字段的文件id
				String fileIds = Util.null2String(rs_1.getString(configEmpty.getAttachmentField()));
				String[] split = fileIds.split(",");
//				转为list
				List<String> list = Arrays.stream(split).collect(Collectors.toList());
//				如果配置了secretField字段
				if (!StringUtils.isNullOrEmpty(secretField)) {
					String secretIds = Util.null2String(rs_1.getString(secretField));
					String[] secretIdArr = secretIds.split(",");
					List<String> secretFieldList = Arrays.stream(secretIdArr).collect(Collectors.toList());
					list.removeAll(secretFieldList);
				}
				String[] docList = docIds.split(",");
				list.addAll(Arrays.stream(docList).collect(Collectors.toList()));
				Map<String, Object> data = ParaMap.create().put(configEmpty.getAttachmentField(), String.join(",", list));
				if (!StringUtils.isNullOrEmpty(secretField)) {
					data.put(secretField, docIds);
				} else {
					data.put(firstAddField, addSuccessValue);
				}
//			修改流程数据，将保密协议的docid更新到流程中
				PrepSqlResultImpl sqlResult = Util.createSqlBuilder().updateSql(billTableName,
						data,
						Util.createPrepWhereImpl().whereAnd("requestid").whereEqual(requestId));
				toolUtil.writeDebuggerLog("sql ： " + sqlResult.getSqlStr() + "  参数： ---> " + sqlResult.getArgs());
				rs.executeUpdate(sqlResult.getSqlStr(), sqlResult.getArgs());
			}
		} catch (Exception e) {
			toolUtil.writeErrorLog("出现错误： " + e);
		}
		return Action.SUCCESS;
	}

	public String copyFile(User user, ConfigEmpty configEmpty, String browseBoxId) {
		ToolUtil toolUtil = new ToolUtil();
//		建模表名称  params.get("tableName")
		String tableName = String.valueOf(configEmpty.getModelTableName());
//		建模字段名 params.get("fieldName")
		String fieldName = String.valueOf(configEmpty.getModelField());
//		附件字段id  params.get("fileFieldId")
		String fileFieldId = String.valueOf(configEmpty.getAttachmentField());
//		配置id params.get("configId")
//		String configId = String.valueOf(configEmpty.getId());
		String configId;
		if ("true".equals(isBrowseBox)) {
//			如果是流程中的某个浏览框，则读取配置文件的浏览框值，否则直接赋值为action中配置的模板id
			configId = browseBoxId;
		} else {
			configId = attachmentTemplateId;
		}
//		流程id params.get("workflowId")
		String workflowId = String.valueOf(configEmpty.getWorkflowType());
		DocTemplateDao docTemplateDao = new DocTemplateDao();
		int[] docIds = null;
		try {
			docIds = docTemplateDao.copyFile(user.getUID(), tableName, fieldName, configId);
		} catch (Exception e) {
			toolUtil.writeErrorLog("复制文件出错： " + e);
			return null;
		}
		if (docIds == null) {
			return null;
		}
		try {
			docTemplateDao.updateFileInfo(workflowId, fileFieldId, docIds);
		} catch (Exception e) {
			toolUtil.writeErrorLog("复制文件更新权限和目录出错： " + e);
			return null;
		}
		toolUtil.writeDebuggerLog("数据更新成功！" + Arrays.toString(docIds));
		List<String> intList = Arrays.stream(docIds).boxed().collect(Collectors.toList())
				.stream().map(String::valueOf).collect(Collectors.toList());
		return String.join(",", intList);
	}

	public String getAttachmentTemplateId() {
		return attachmentTemplateId;
	}

	public void setAttachmentTemplateId(String attachmentTemplateId) {
		this.attachmentTemplateId = attachmentTemplateId;
	}

	public String getIsBrowseBox() {
		return isBrowseBox;
	}

	public void setIsBrowseBox(String isBrowseBox) {
		this.isBrowseBox = isBrowseBox;
	}

	public String getFirstAddField() {
		return firstAddField;
	}

	public void setFirstAddField(String firstAddField) {
		this.firstAddField = firstAddField;
	}

	public String getFirstAddValue() {
		return firstAddValue;
	}

	public void setFirstAddValue(String firstAddValue) {
		this.firstAddValue = firstAddValue;
	}

	public String getSecretField() {
		return secretField;
	}

	public void setSecretField(String secretField) {
		this.secretField = secretField;
	}

	public String getAddSuccessValue() {
		return addSuccessValue;
	}

	public void setAddSuccessValue(String addSuccessValue) {
		this.addSuccessValue = addSuccessValue;
	}
}
